'use strict';
const {
	verifyToken
} = require('wx-common');
const db = uniCloud.database();
const cartCollection = db.collection('xxf-cart');
const dbCmd = db.command;
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event);
	const {
		action,
		token,
		uid,
	} = event;
	if (!verifyToken(token)) {
		return {
			code: 401,
			message: 'Token无效'
		};
	}
	if (!uid) {
		return {
			msg: '用户ID参数错误！',
			code: 0,
			data: null
		};
	}
	switch (action) {
		case 'addToCart':
			return addToCart(event);
		case 'editCart':
			return editCart(event);
		case 'deleteCart':
			return deleteCart(event);
		case 'getCartList':
			return getCartList(event);
		default:
			return {
				msg: 'Invalid action！',
					code: 0,
					data: null
			};
	}
};
async function getCartList(params) {
	const {
		uid
	} = params;
	const cartRes = await cartCollection.where({
		uid
	}).orderBy('update_time', 'desc').get();
	console.log('cartRes1: ', cartRes);
	if (cartRes.data && cartRes.data.length > 0) {
		// for (let i = 0; i < cartRes.data.length; i++) {
		// 	const infoRes = await uniCloud.callFunction({
		// 		name: 'xxf-product',
		// 		data: {
		// 			action: "getProductDetail",
		// 			uid,
		// 			id: cartRes.data[i].product_info._id
		// 		}
		// 	});
		// 	console.log('infoRes: ', infoRes);
		// 	cartRes.data[i].product_info = infoRes.result.data;
		// }
		// console.log('cartRes2: ', cartRes);
		return {
			msg: '',
			code: 1,
			data: {
				list: cartRes.data,
			}
		};
	} else {
		return {
			msg: '暂无数据！',
			code: 0,
			data: {
				total: 0,
				list: []
			}
		};
	}
}
async function deleteCart(params) {
	const {
		uid,
		cartIds,
	} = params;
	const rmRes = await cartCollection.where({
		uid,
		_id: dbCmd.in(cartIds)
	}).remove();
	console.log("rmRes: ", rmRes);
	if (rmRes && rmRes.deleted) {
		return {
			msg: '删除成功！',
			code: 1,
			data: rmRes
		}
	} else {
		return {
			msg: '删除失败！',
			code: 0,
			data: null
		}
	}
}
async function editCart(params) {
	const {
		uid,
		cartId,
		product_id,
		spu_id,
		product_info,
		spu_info,
		count,
	} = params;
	const haveRes = await cartCollection.where({
		uid,
		_id: cartId
	}).get();
	console.log("haveRes: ", haveRes);
	if (haveRes.data && haveRes.data.length > 0) {
		// 购物车中已经存在，只需要更新数量
		let haveObj = haveRes.data[0];
		const updateRes = await cartCollection.where({
			uid,
			_id: cartId
		}).update({
			product_id,
			spu_id,
			product_info,
			spu_info,
			count,
			update_time: Date.now(),
		});
		console.log("updateRes: ", updateRes);
		if (updateRes.updated === 1) {
			const whereRes = await cartCollection.where({
				uid,
				_id: cartId
			}).get();
			console.log("whereRes: ", whereRes);
			const cartObj = whereRes.data[0];
			return {
				msg: '',
				code: 1,
				data: {
					...cartObj
				}
			}
		} else {
			return {
				msg: '更新失败！',
				code: 0,
				data: null
			}
		}
	} else {
		return {
			msg: 'ID错误！',
			code: 0,
			data: null
		}
	}

}
async function addToCart(params) {
	const {
		uid,
		product_info,
		spu_info,
		count,
		status
	} = params;
	const key = `${product_info._id}_${spu_info.name}`;
	const haveRes = await cartCollection.where({
		uid,
		key
	}).get();
	console.log("haveRes: ", haveRes);
	if (haveRes.data && haveRes.data.length > 0) {
		// 购物车中已经存在，只需要更新数量
		let haveObj = haveRes.data[0];
		const updateRes = await cartCollection.where({
			uid,
			key,
		}).update({
			product_info,
			spu_info,
			count: haveObj.count + count,
			update_time: Date.now(),
		});
		console.log("updateRes: ", updateRes);
		if (updateRes.updated === 1) {
			const whereRes = await cartCollection.where({
				uid,
				key,
			}).get();
			console.log("whereRes: ", whereRes);
			const cartObj = whereRes.data[0];
			return {
				msg: '',
				code: 1,
				data: {
					...cartObj
				}
			}
		} else {
			return {
				msg: '更新失败！',
				code: 0,
				data: updateRes
			}
		}
	} else {
		// 购物车中不存在，需要添加
		const addRes = await cartCollection.add({
			uid,
			key,
			product_info,
			spu_info,
			count,
			create_time: Date.now(),
			update_time: Date.now(),
		})
		console.log("addRes: ", addRes);
		const whereRes = await cartCollection.where({
			uid,
			key,
		}).get();
		console.log("whereRes: ", whereRes);
		const cartObj = whereRes.data[0];
		return {
			msg: '',
			code: 1,
			data: {
				...cartObj
			}
		}
	}
}